package com.mgkj.aop;

import cn.hutool.core.date.StopWatch;

import com.mgkj.annotation.Log;
import com.mgkj.common.result.Result;
import com.mgkj.common.utils.TimeUtils;
import com.mgkj.entity.UserLog;
import com.mgkj.service.MessagepzService;
import com.mgkj.service.UserLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.UUID;


/**
 * 请求响应日志 AOP
 *
 **/
@Aspect
@Component
@Slf4j
public class TimeInterceptor {

    @Autowired
    private UserLogService userLogService;

    @Resource
    private MessagepzService messagepzService;

    private static final String TRACE_ID = "TRACE_ID";

    /**
     * 执行拦截
     */
    @Around("execution(* com.mgkj.controller..*.*(..))")
    public Object doInterceptor(ProceedingJoinPoint point) throws Throwable {
        // 计时
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        // 获取请求路径
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 生成请求唯一 id
        String requestId = UUID.randomUUID().toString();
        String url = httpServletRequest.getRequestURI();
        String startTime = TimeUtils.getFullNowTime();
        // 获取请求参数
        Object[] args = point.getArgs();
        String reqParam = "[" + StringUtils.join(args, ", ") + "]";
//        System.out.println(reqParam);

        String tid = requestId;
        MDC.put(TRACE_ID, tid);

        if(!url.contains("mqtt") && !url.contains("Znx")) {
            // 输出请求日志
            log.info("request start，id: {}, path: {}, ip: {}, params: {}", requestId, url,
                    httpServletRequest.getRemoteHost(), reqParam);
        }

        // 获取方法签名
        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        Method method = methodSignature.getMethod();

        boolean flag = false;
        String module = "";
        // 获取方法注解
        Annotation[] methodAnnotations = method.getAnnotations();
        for (Annotation annotation : methodAnnotations) {
            if (annotation instanceof Log) {
                Log myAnnotation = (Log) annotation;
                module = myAnnotation.value();
                // 这里可以根据方法注解做相应的处理
                // 示例：输出方法注解信息
//                log.info("swagger value: {}", myAnnotation.title());
                flag = true;
                break;
            }
        }
        // 执行原方法
        Object result = point.proceed(args);
        // 输出响应日志
        stopWatch.stop();
        long totalTimeMillis = stopWatch.getTotalTimeMillis();

//        if(!url.contains("mqtt")) {
//            log.info("request end, id: {}, cost: {}ms", requestId, totalTimeMillis);
//        }

        if (flag) {
//            DynamicDataSourceContextHolder.clear();
//            DynamicDataSourceContextHolder.push("demo");
            Result res = (Result) result;
//            String resultString = Json.pretty(res);
            String resultString = result.toString();
//            System.out.println("+++++++++++++----------------*************");
//            System.out.println(resultString);
//            this.messagepzService.PushMessage(url,resultString,reqParam);
            userLogService.mySave(new UserLog(requestId, "", startTime,
                    url, httpServletRequest.getRemoteHost(), Long.valueOf(totalTimeMillis).toString(),
                    resultString, reqParam, module));
        }
        MDC.remove(TRACE_ID);
        return result;
    }

}
